﻿//=============================================================
// Copyright (C) 2011 iSun Studio 软件工作室
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 通用的单笔数据增删改
//        json:前端提交的数据
//        action:操作,insert,update,delete
//        entity:实体对象名称
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉           
//=============================================================
using System;
using System.Web;
using System.Text;
using iSun.Common;


using iSun.Model;
using iSun.BLL.Base;
using iSun.Web.UI.Controls;
using iSun.HR.Entity;
using iSun.Entity;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using iSun.DAL.DBExtend;
using iSun.Entity;

namespace iSun.WebApp.AjaxData
{

    public partial class DataSave : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //DateTime dt = DateTime.Now;
            string strAction = this.GetStringFromQueryString("action", "");
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strTable = this.GetStringFromQueryString("table", "");
            string strFrom = this.GetStringFromQueryString("from", "");
            ///用于表单自定义
            string strFormID = this.GetStringFromQueryString("fromid", Guid.Empty.ToString());
            string flag = this.GetStringFromQueryString("flag", "");
            string strJson = "";
            if (flag == "1")
            {
                string Forms = iSunContext.Request.Form[0].ToString();
                strJson = Forms;
            }
            else
            {
                strJson = this.GetStringFromQueryString("json", "");
            }

            CreateBussniess(strEntity);
            BaseEntity instance = null;
            try
            {
                instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            }
            catch { }
            if (instance == null)
            {
                strTable = strEntity;
            }
            if (strTable == "" || "insert,update,delete".IndexOf(strAction) < 0) // 有实体的
            {
                string msg = "";
                switch (strAction)
                {
                    case "":
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                    case "insert":
                        try
                        {
                            InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "delete":
                        delete(strEntity, strJson);
                        break;
                    case "setRight":
                        SetRight(strJson);
                        break;
                    case "setQuery":
                        SetQuery(strJson);
                        break;
                    case "setUserLayout":
                        SetUserLayout(strJson);
                        break;
                    case "setTimeResult":
                        SetTimeResult(strJson);
                        break;
                    case "setNoCardDataConfig":
                        SetNoCardDataConfig(strJson);
                        break;
                    case "confirmWorkResult":
                        ConfirmWorkResult(strEntity, strJson);
                        break;
                    case "SavePostSkill":
                        SavePostSkill(strEntity, strJson);
                        break;
                    case "SaveEmpSkill":
                        SaveEmpSkill(strEntity, strJson);
                        break;
                    case "setEmpSkill":
                        SetEmpSkill(strJson);
                        break;
                    case "InitDataListTemplate":
                        if (instance == null)
                        {
                            strTable = strEntity;
                        }
                        else
                        {
                            strTable = instance.GetTableName();
                        }
                        InitDataListTemplate(strTable, strEntity);
                        break;
                    case "setTableStruc":
                        try
                        {
                            SetTableStruc(strJson);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "deleteFile":
                        string path = this.GetStringFromQueryString("path", "");
                        string file = this.GetStringFromQueryString("file", "");
                        DeleteFile(path, file);
                        break;
                    default:
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                }
            }
            else // 没有实体的
            {
                switch (strAction)
                {
                    case "insert":
                        Insert(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "update":
                        Update(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "delete":
                        Delete(strTable, strJson);
                        break;
                }
            }
        }


        /// <summary>
        /// 创建业务逻辑实例
        /// </summary>
        /// <param name="entityName"></param>
        private void CreateBussniess(string entityName)
        {
            this._bll = BaseBussnies.CreateInstance(entityName);
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        /// <param name="action"></param>
        private void InsertOrUpdate(string strEntity, string strJson, string action)
        {
            CreateBussniess(strEntity);
            BaseEntity instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            _bll.entity = instance;
            System.Guid? keyValue = instance.GetKeyFieldValue();
            //BaseEntity item = instance.
            //数据验证
            string strMsg = instance.CheckData();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            strMsg = instance.GetDataCheckMessage();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            bool b;
            if (action == "")
            {
                if (instance.GetKeyFieldValue() == new System.Guid())
                {
                    action = "insert";
                }
            }
            string checkResult = _bll.CheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            checkResult = "";// _bll.CheckData(instance, this.Page);
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }


            //// 如果是批量数据操作
            if (this.GetStringFromQueryString("isBatch", "false") == "true")
            {
                Insert(strEntity, strJson);
                return;
            }
            strMsg = "";
            //instance.Save();
            if (action == "insert")
            {
                if (null == (Globals.GetPropertyValue(instance, "AddUser") as Guid?) || (Globals.GetPropertyValue(instance, "AddUser") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                    Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                }
                //if (EntityName == "MQOrgBody")
                //{
                //    Guid obid = Guid.NewGuid();
                //    Globals.SetPropertyValue(instance, "obid", obid);
                //    b = _bll.Insert(out strMsg);
                //    try
                //    {
                //        string substr = strJson.Substring(strJson.Length - 38, 36);
                //        iSun.Entity.MQOTB mqt = new ZX.SYS.Library.MQOTB();
                //        mqt.otbid = Guid.NewGuid();
                //        mqt.otid = new Guid(substr);
                //        mqt.obid = obid;
                //        BaseBussnies bmqt = new BaseBussnies(mqt);
                //        bmqt.Insert();
                //    }
                //    catch (Exception) { }
                //}
                //else
                {
                    b = _bll.Insert(out strMsg);
                }

                if (EntityName == "SysTable")
                {
                    DBTable dbTable = SqlDBTable.Instance;
                    dbTable.CreateTable((instance as SysTable).TableName);
                }
            }
            else
            {
                if (null == (Globals.GetPropertyValue(instance, "AddUser") as Guid?) || (Globals.GetPropertyValue(instance, "AddUser") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "AddUser", this.UserId);
                    Globals.SetPropertyValue(instance, "AddTime", System.DateTime.Now);
                }
                checkResult = _bll.EditCheckData();
                if (false == string.IsNullOrEmpty(checkResult))
                {
                    HttpContext.Current.Response.Write(checkResult);
                    return;
                }
                b = _bll.Update(out strMsg);
            }
            if (b)
            {
                try
                {
                   //iSun.BLL.BDataLog.Instance.SaveLog(this.UserId, instance, action);
                }
                catch { };
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                HttpContext.Current.Response.Write(strMsg);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void delete(string strEntity, string strJson)
        {
            string checkResult = _bll.DeleteCheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            BaseEntity instance = (BaseEntity)Reflection.CreateEntitysInstance(strEntity);
            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(instance);
            BaseBussnies bll = _bll;
            bll.entity = instance;

            string key = instance.getKey();
            if (string.IsNullOrEmpty(strJson))
            {
                strJson = this.GetStringFromQueryString("id", "");
                bll.delete(key + "='" + strJson + "'");
                try
                {
                    //BDataLog.Instance.SaveLog(this.UserId, instance, "delete");
                }
                catch { }
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                string[] strarr = strJson.Split(',');
                foreach (var s in strarr)
                {
                    bll.delete(key + "='" + s + "'");
                }
                HttpContext.Current.Response.Write("1");
            }
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="TableName">表名/实体名</param>
        void InitDataListTemplate(string TableName, string EntityName)
        {
            string sql = string.Format("Exec sp_InitDataListTemplate '{0}','{1}'", TableName, EntityName);
            DbSql dbsql = new DbSql();
            //this.BatchSave(
            if (dbsql.ExecuteSql(sql) > 0)
            {
                iSunContext.Response.Write("1");
            }
            else
            {
                iSunContext.Response.Write("0");
            }
        }

        /// <summary>
        /// 确认考勤结果
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void ConfirmWorkResult(string strEntity, string strJson)
        {
            strJson = "'" + strJson.Replace(",", "','") + "'";
            string sql = string.Format("Update wkWorkResult set IsValidate='Y' Where ID in ({0})", strJson);
            DbSql dbsql = new DbSql();
            if (dbsql.ExecuteSql(sql) > 0)
            {
                iSunContext.Response.Write("1");
            }
            else
            {
                iSunContext.Response.Write("0");
            }
        }

        /// <summary>
        /// 保存职位技能要求
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="strJson"></param>
        private void SavePostSkill(string entity, string strJson)
        {
            //try
            //{
            //    var list = (List<V_datSkillLevel>)Globals.JSonToObject<List<V_datSkillLevel>>(strJson);
            //    string postID = this.GetStringFromQueryString("postID", Guid.Empty.ToString());
            //    string sql = "select ID from {0} where postid='{1}' and SkillID='{2}' and SkillLevelID='{3}' ";
            //    string insertsql = "insert into {0}(ID,PostID,SkillID,SkillLevelID) values(newid(),'{1}','{2}','{3}')";
            //    DbSql dbsql = new DbSql();
            //    foreach (var item in list)
            //    {
            //        //先查询是否存在
            //        if (dbsql.ExecuteQuery(string.Format(sql, entity, postID, item.SkillID, item.SkillLevelID)).Rows.Count < 1)
            //        {
            //            //dbsql.ExecuteSql(string.Format(sql, entity, postID, item.SkillID, item.SkillLevelID));
            //            dbsql.ExecuteSql(string.Format(insertsql, entity, postID, item.SkillID, item.SkillLevelID));
            //        }
            //    }
            //    iSunContext.Response.Write("1");
            //}
            //catch (Exception ex)
            //{
            //    iSunContext.Response.Write("0");
            //}
        }

        /// <summary>
        /// 保存员工技能
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="strJson"></param>
        private void SaveEmpSkill(string entity, string strJson)
        {
            //try
            //{
            //    var list = (List<V_datSkillLevel>)Globals.JSonToObject<List<V_datSkillLevel>>(strJson);
            //    string empID = this.GetStringFromQueryString("EmpID", Guid.Empty.ToString());
            //    string sql = "select ID from {0} where employeeid='{1}' and SkillID='{2}' and SkillLevelID='{3}' ";
            //    string insertsql = "insert into {0}(ID,employeeid,SkillID,SkillLevelID,level,skillName) values(newid(),'{1}','{2}','{3}','{4}','{5}')";
            //    DbSql dbsql = new DbSql();
            //    foreach (var item in list)
            //    {
            //        //先查询是否存在
            //        if (dbsql.ExecuteQuery(string.Format(sql, entity, empID, item.SkillID, item.SkillLevelID)).Rows.Count < 1)
            //        {
            //            dbsql.ExecuteSql(string.Format(insertsql, entity, empID, item.SkillID, item.SkillLevelID, item.Level.ToString(), item.SkillName));
            //        }
            //    }
            //    iSunContext.Response.Write("1");
            //}
            //catch (Exception ex)
            //{
            //    iSunContext.Response.Write("0");
            //}
        }


        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="strJson"></param>
        private void SetRight(string strJson)
        {
            var list = (List<V_FunctionRight>)Globals.JSonToObject<List<V_FunctionRight>>(strJson);
            string strSql = "update SysRoleFunction set BarItems='{0}',OperateRangeType='{2}',Depts='{3}',Condition='{4}' where RoleFunctionID='{1}'\n";
            StringBuilder sSql = new StringBuilder("");
            foreach (var item in list)
            {
                sSql.Append(string.Format(strSql, item.BarItem, item.RoleFunctionID, item.OperateRangeType, item.Depts, item.Condition));
            }
            BaseBussnies bll = new BaseBussnies();
            if (sSql.ToString() == "")
            {
                iSunContext.Response.Write("没有数据!");
                return;
            }
            int i = bll.RunSqlCommand(sSql.ToString());
            if (i > 0)
            {
                iSunContext.Response.Write("1");
            }
            else
            {
                //写日志
                WriteExpLog();
                iSunContext.Response.Write("0");
            }
        }

        void SetUserLayout(string strJson)
        {
            BaseBussnies bll = new BaseBussnies();
            UserListTemplate userLT = bll.GetEntityByCondition<UserListTemplate>("functionID='" + this.FunctionID + "' and AddUser='" + this.UserId + "'");
            if (userLT == null)
            {
                userLT = new UserListTemplate();
            }
            userLT.FunctionID = (Guid)FunctionID;
            userLT.AddUser = (Guid)this.UserId;
            userLT.DataJSON = strJson;
            userLT.EntityName = this.EntityName;
            bll.entity = userLT;
            if (userLT.ID == Guid.Empty)
            {
                bll.Insert();
            }
            else
            {
                bll.Update();
            }
            iSunContext.Response.Write("1");

        }

        /// <summary>
        /// 设置项目中心的考勤结果
        /// </summary>
        /// <param name="strJson"></param>
        void SetTimeResult(string strJson)
        {
            //IList<ZX.EHR.Library.wkProjectWorkResult> list = (List<wkProjectWorkResult>)Globals.JSonToObject<List<wkProjectWorkResult>>(strJson);
            //BaseBussnies bll = new BaseBussnies();
            //foreach (var entity in list)
            //{
            //    bll.entity = entity;
            //    bll.Update();
            //}
            //iSunContext.Response.Write("1");
        }

        /// <summary>
        /// 保存无需打卡列表页面
        /// </summary>
        /// <param name="strJson"></param>
        void SetNoCardDataConfig(string strJson)
        {
            //var list = (List<wkNoCardDataConfig>)Globals.JSonToObject<List<wkNoCardDataConfig>>(strJson);
            //string sql = "update wkNoCardDataConfig set FrmDate='{0}',EndDate='{1}' where ID='{2}'";
            //DbSql dbsql = new DbSql();
            //foreach (var item in list)
            //{
            //    string frmDate = item.FrmDate;
            //    string endDate = item.EndDate;
            //    DateTime t1 = DateTime.MinValue;
            //    if (frmDate.Length > 0)
            //    {
            //        frmDate = frmDate.Substring(0, 10);
            //        DateTime.TryParse(frmDate, out t1);
            //        frmDate = t1.ToString("yyyy-MM-dd");
            //    }
            //    if (endDate.Length > 0)
            //    {
            //        endDate = endDate.Substring(0, 10);
            //        DateTime.TryParse(endDate, out t1);
            //        endDate = t1.ToString("yyyy-MM-dd");
            //    }
            //    dbsql.ExecuteSql(string.Format(sql, frmDate, endDate, item.ID));
            //}
            //iSunContext.Response.Write("1");
        }

        /// <summary>
        /// 保存员工技能列表，主要是起始、终止日期；是否有效字段。
        /// </summary>
        /// <param name="strJson"></param>
        void SetEmpSkill(string strJson)
        {
            //var list = (List<hrEmployeeSkills>)Globals.JSonToObject<List<hrEmployeeSkills>>(strJson);
            //string sql = "update hrEmployeeSkills set {0},{1},ISEffective='{2}' where ID='{3}'";
            //DbSql dbsql = new DbSql();
            //foreach (var item in list)
            //{
            //    string frmDate = item.BeginDate.ToString();
            //    string endDate = item.EndDate.ToString(); ;
            //    DateTime t1 = DateTime.MinValue;
            //    if (frmDate.Length > 0)
            //    {
            //        frmDate = frmDate.Substring(0, 10);
            //        DateTime.TryParse(frmDate, out t1);
            //        if (t1.Year > 1)
            //        {
            //            frmDate = t1.ToString("yyyy-MM-dd");
            //            frmDate = string.Format("BeginDate='{0}'", frmDate);
            //        }
            //        else
            //        {
            //            frmDate = "BeginDate=null";
            //        }
            //    }
            //    if (endDate.Length > 0)
            //    {
            //        endDate = endDate.Substring(0, 10);
            //        DateTime.TryParse(endDate, out t1);
            //        if (t1.Year > 1)
            //        {
            //            endDate = t1.ToString("yyyy-MM-dd");
            //            endDate = string.Format("EndDate='{0}'", endDate);
            //        }
            //        else
            //        {
            //            endDate = "EndDate=null";
            //        }
            //    }
            //    dbsql.ExecuteSql(string.Format(sql, frmDate, endDate, item.ISEffective, item.ID));
            //}
            //iSunContext.Response.Write("1");
        }

        /// <summary>
        /// 批保存
        /// </summary>
        /// <param name="strJson"></param>
        void BatchSave(string strJson)
        {

        }

        /// <summary>
        /// 设置表结构
        /// </summary>
        /// <param name="strJson"></param>
        public void SetTableStruc(string strJson)
        {
            List<SysTableField> list = Globals.JSonToObject<List<SysTableField>>(strJson);
            DBTable dbTable = SqlDBTable.Instance;
            foreach (SysTableField entity in list)
            {
                if (entity.TableFieldID == Guid.Empty)
                {
                    string strFiled = entity.FiledType;
                    switch (strFiled.ToLower())
                    {
                        case "varchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nvarchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "char":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "nchar":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;
                        case "ntext":
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                        case "bigint":
                            strFiled = entity.FiledType;
                            break;
                        case "int":
                            strFiled = entity.FiledType;
                            break;
                        case "bit":
                            strFiled = entity.FiledType;
                            break;
                        case "datetime":
                            strFiled = entity.FiledType;
                            break;
                        case "smalldatetime":
                            strFiled = entity.FiledType;
                            break;
                        case "date":
                            strFiled = entity.FiledType;
                            break;
                        case "uniqueidentifier":
                            strFiled = entity.FiledType;
                            break;
                        case "money":
                            strFiled = entity.FiledType;
                            break;

                        case "binary":
                            strFiled = entity.FiledType;
                            break;
                        case "float":
                            strFiled = entity.FiledType;
                            break;
                        case "image":
                            strFiled = entity.FiledType;
                            break;
                        case "numeric":
                            strFiled = entity.FiledType + "(" + entity.Length + ")";
                            break;
                        case "real":
                            strFiled = entity.FiledType;
                            break;
                        default:
                            strFiled = entity.FiledType + "(" + entity.Length.Split(',')[0] + ")";
                            break;

                    }


                    dbTable.AddCol(entity.TableName, entity.FieldName, strFiled);
                    dbTable.AddColNotes(entity.TableName, entity.FieldName, entity.Notes);
                }

            }
            iSunContext.Response.Write("1");
        }


        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="TableName"></param>
        public void SetTable(string TableName)
        {
            DBTable dbTable = SqlDBTable.Instance;
            dbTable.CreateTable(TableName);
        }

        /// <summary>
        /// 设置查询
        /// </summary>
        /// <param name="strJson"></param>
        private void SetQuery(string strJson)
        {
            QuerySolution entity = (QuerySolution)Globals.JSonToObject<QuerySolution>(strJson);
            entity.BaseEntityState = WorkState.New;
            entity.EntityName = this.EntityName;
            entity.FunctionID = this.FunctionID;
            entity.AddUser = this.UserId;
            entity.AddTime = DateTime.Now;
            string action = "";

            if (entity.QueryId == null || entity.QueryId == Guid.Empty)
            {
                action = "insert";
                entity.QueryId = Guid.Empty;
            }

            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            _bll.entity = entity;
            if (entity.IsDefault == "Y")
            {
                _bll.RunSqlCommand("update Set_QuerySolution set IsDefault='N' where AddUser='" + this.UserId + "' and FunctionID='" + entity.FunctionID + "'");
            }
            bool b;
            if (action == "insert")
            {

                b = _bll.Insert();
            }
            else
            {
                b = _bll.Update();
            }
            if (b)
            {
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="File"></param>
        private void DeleteFile(string FilePath, string File)
        {
            string path = this.MapPath(FilePath);
            System.IO.File.Delete(path + File);
        }

        #region No Entity
        /// <summary>
        /// 实现没有实体的操作
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Insert(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid", Guid.Empty.ToString()), table);
            string[] strKeyArrary = instance.GetKey();
            if (strKeyArrary != null)
            {
                instance.TableKey = strKeyArrary[0];
                instance.KeyType = strKeyArrary[1];
            }
            instance.CreateDT();
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson = strArray[0];//json;// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("AddUser"))
            {
                instance.FieldValue["AddUser"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("AddTime"))
            {
                instance.FieldValue["AddTime"] = System.DateTime.Now;
            }

            if (instance.FieldValue.ContainsKey("RecID"))
            {
                instance.FieldValue.Remove("RecID");
            }
            instance.SetValue(instance.FieldValue);
            //instance.SetPropertyValue("", "");
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            sqlCommand.Append(bll.GetSqlCommand(instance));
            string strMsg = "";
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strKeyArrary = DetailInstance.GetKey();
                        if (strKeyArrary != null)
                        {
                            DetailInstance.TableKey = strKeyArrary[0];
                            DetailInstance.KeyType = strKeyArrary[1];
                        }
                        DetailInstance.CreateDT();
                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);

                        if (DetailInstance.KeyType == "uniqueidentifier")
                        {
                            if (DetailInstance[DetailInstance.TableKey].ToString() == "")
                            {
                                DetailInstance[DetailInstance.TableKey] = Guid.NewGuid();
                            }
                        }

                        if (DetailInstance.FieldValue.ContainsKey("RecID"))
                        {
                            DetailInstance.FieldValue.Remove("RecID");
                        }
                        if (((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).TableKey] == null || ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey].ToString() != string.Empty)
                        {
                            ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).TableKey] = Guid.NewGuid();
                        }
                        //entity.SetFieldValue(entity, e.FieldName, MasterEntity.GetKeyFieldValue());
                        //DetailInstance.SetFieldValue(DetailInstance, DetailInstance.GetFKey()[0].FieldName, instance.GetKeyFieldValue());
                        bll.entity = DetailInstance;
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                    int i = bll.RunSqlCommand(sqlCommand.ToString(), out strMsg);
                    if (i > -1)
                    {
                        iSunContext.Response.Write("1");
                        return;
                    }
                    else
                    {
                        iSunContext.Response.Write(strMsg);
                        return;
                    }
                }
            }
            if (table.Substring(0, 4) != "bpm_")//非BPM的表格
            {
                try
                {
                    this.InsertOrUpdate(table, json, GetStringFromQueryString("action", "insert"));
                    return;
                }
                catch { };
            }
            // 
            strMsg = "";
            if (bll.Insert(out strMsg))
            {
                iSunContext.Response.Write("1");
            }
            else
            {
                iSunContext.Response.Write(strMsg);
            }
        }

        public void Update(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid", Guid.Empty.ToString()), table);
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            instance.CreateDT();
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson = strArray[0];// ZX.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("AddUser"))
            {
                instance.FieldValue["EditWho"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("AddTime"))
            {
                instance.FieldValue["EditDate"] = System.DateTime.Now;
            }

            instance.SetValue(instance.FieldValue);
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            sqlCommand.Append(bll.GetSqlCommand(instance));
            // 将旧的数据清空
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    int _count = 0;
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strArray = DetailInstance.GetKey();
                        if (strArray != null)
                        {
                            DetailInstance.TableKey = strArray[0];
                            DetailInstance.KeyType = strArray[1];
                        }
                        DetailInstance.CreateDT();

                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);
                        bll.entity = DetailInstance;
                        // 加入
                        if (_count == 0)
                        {
                            IList<SysTableFKey> fkList = DetailInstance.GetFKey();
                            if (fkList != null)
                            {
                                foreach (var e in fkList)
                                {
                                    if (e.FKTableName == instance.GetTableName())
                                    {
                                        sqlCommand.Append(string.Format("Delete from {0} where {1}", DetailInstance.GetTableName(), e.FieldName + "='" + instance.GetTableIdValue() + "'"));
                                    }

                                }
                            }
                        }
                        _count = 1;
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                }
                int i = bll.RunSqlCommand(sqlCommand.ToString());
                Response.Write("1");
                return;
            }
            if (bll.Update())
            {
                iSunContext.Response.Write("1");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Delete(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.TableKey = strArrary[0];
                instance.KeyType = strArrary[1];
            }
            string[] ids = json.Split(',');
            try
            {
                foreach (string id in ids)
                {
                    instance.Delete(id);
                }
                iSunContext.Response.Write("1");
            }
            catch (Exception e)
            {
                iSunContext.Response.Write(e.Message);
            }
        }
        #endregion


        /// <summary>
        /// 初始数据
        /// </summary>
        /// <param name="strFormID"></param>
        /// <param name="strEntity"></param>
        private string GetDetailTable(string strFormID, string strEntity)
        {
            if (strFormID == "")
            {
                strFormID = Guid.Empty.ToString();
            }
            SysCustomDefineForm FormEntity = _bll.GetEntityByCondition<SysCustomDefineForm>("FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'");
            if (FormEntity != null)
            {
                return GetDetailTable(FormEntity.DetailsJson);
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="DetailsJson"></param>
        /// <returns></returns>
        private string GetDetailTable(string DetailsJson)
        {
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                foreach (var _detail in list)
                {
                    return _detail.DetailsTableName;
                }
                //DetailsInstance = _details.ToString();
            }
            return "";
        }
    }
}